let Collider = require("Collider");

cc.Class({
    extends: cc.Component,

    properties: {
        // 暂存 enemyManager 对象的引用
        enemyManager: {
            default: null,
            serializable: false
        },

        // collider type : 使用于碰撞检测时，根据碰撞类型执行不同的动作
        COLLIDER_TYPE: {
            visible: false,
            default: Collider.type.ENEMY,
            type: cc.Integer,
        },
        
        // alive timer
        timer : 0,
        // alive max time in second
        aliveMaxTime : 4,
        
        // speed
        speed : 500,
        // hp
        maxHp : 5,
    },

    // use this for initialization
    onLoad: function () {
    },
    
    init: function (enemyManager) {
        if (enemyManager) {
            this.enemyManager = enemyManager;
        }
        this.alive = true;
        this.timer = 0;
        this.hp = this.maxHp;
    },

    unuse: function () {
        this.timer = 0;
        this.alive = false;
        this.hp = 0;
        this.enemyManager = null;
    },

    reuse: function (enemyManager) {
        this.enemyManager = enemyManager; // get 中传入的管理类实例
    },
    
    hit : function (attack) {
        if (attack) {
            this.hp -= attack;
        } else {
            this.hp--;
        }
        if (this.hp <= 0) {
            this.destory();
        }
    },

    destory: function () {
        this.enemyManager.put(this.node);
    },
    
    onCollisionEnter: function (other, self) {
        if (this.alive) {
            let ocpt = other.node.getComponent(other.node.name);
            if (ocpt.COLLIDER_TYPE === Collider.type.PLAYER) {
                this.destory();
            } else if (ocpt.COLLIDER_TYPE === Collider.type.PLAYER_BULLET) {
                this.hit();
            }
        }
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        if (!this.alive) return ;
        // update timer
        this.timer += dt;
        // 如果在生存周期之内
        if (this.timer < this.aliveMaxTime) {
            this.node.y -= this.speed * dt;
        } else {
            this.alive = false;
            this.enemyManager.put(this.node);
        }
    },
});
